package com.gml.jdk.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.FixedValue;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @ClassName : SampleClass
 * @Description : cglib实例
 * @Author : gml
 * @Date: 2020-10-19 16:44
 */
public class CglibTest {

    public String test(){
        System.out.println("hello cglib");
        return "haha";
    }

    /**
     * @param
     * @description 方法代理
     * @author gml
     * @date 2020/10/20 11:30
     * @return
     * @throws
     */
    public static void test1(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(CglibTest.class);
        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object obj, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("before method run---");
                Object result = methodProxy.invokeSuper(obj, objects);
                System.out.println("after method run ---");
                return result;
            }
        });

        CglibTest cglibTest = (CglibTest) enhancer.create();
        cglibTest.test();
    }

    public static void test2(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(CglibTest.class);
        enhancer.setCallback(new FixedValue() {
            public Object loadObject() throws Exception {

                return "hello cglib";
            }
        });

        CglibTest cglibTest = (CglibTest) enhancer.create();
        System.out.println(cglibTest.test());
        System.out.println(cglibTest.toString());
        System.out.println(cglibTest.getClass());
        System.out.println(cglibTest.hashCode());
    }

    /**
     * @param args
     * @description
     * @author gml
     * @date 2020/10/19 16:57
     * @return
     * @throws
     */
    public static void main(final String[] args) {
        test1();
//        test2();
    }
}
